﻿#include <iostream>  
#include <mongocxx/client.hpp>  
#include <mongocxx/instance.hpp>  
#include <bsoncxx/builder/stream/document.hpp>  
#include <bsoncxx/json.hpp>  

int main() {  
    try {  
        // 初始化 MongoDB 驱动实例（整个程序只需一次）  
        mongocxx::instance inst{};  

        // 创建客户端连接（默认连接到 localhost:27017）  
        mongocxx::client conn{ mongocxx::uri{"mongodb://trader_ljz:liu%40quant123B@121.41.4.141:27017/index_futures_arb?authSource=admin"} };  

        // 获取数据库和集合 
        auto db = conn["index_futures_arb"];  
        auto collection = db["test1"];  

        // 创建文档  
        auto doc = bsoncxx::builder::stream::document{}  
            << "app" << "MongoDB VS2022 Demo"  
            << "timestamp" << bsoncxx::types::b_date{ std::chrono::system_clock::now() }  
            << "status" << "success"  
            << "method" << "CMake"  
            << bsoncxx::builder::stream::finalize;  

        // 插入文档  
        auto result = collection.insert_one(doc.view());  

        if (result) {  
            std::cout << "✅ 文档插入成功! ID: "  
                << result->inserted_id().get_oid().value.to_string()  
                << std::endl;  
        }  
        else {  
            std::cerr << "❌ 文档插入失败" << std::endl;  
        }  

        // 查询文档数量  
        std::cout << "集合中文档总数: " << collection.count_documents({}) << std::endl;  

    }  
    catch (const std::exception& e) {  
        std::cerr << "⚠️ MongoDB 错误: " << e.what() << std::endl;  
        return 1;  
    }  
    return 0;  
}
